import time
from os import path

import yaml
from appium import webdriver

from common import appium_start, check_port, release_port, adb_connect, check_devices
from config import settings


def appium_desired(config_file):
    with open(path.join(settings.CONFIG_PATH, config_file), 'r', encoding='utf-8') as file:
        data = yaml.load(file, Loader=yaml.FullLoader)
    app_path = path.join(settings.APPS_PATH, data['appname'])
    desired_caps = {}
    desired_caps['platformName'] = data['platformName']
    desired_caps['platformVersion'] = data['platformVersion']
    desired_caps['deviceName'] = data['deviceName']
    desired_caps['udid'] = data['udid']
    desired_caps['app'] = app_path
    desired_caps['appPackage'] = data['appPackage']
    desired_caps['appActivity'] = data['appActivity']
    desired_caps['noReset'] = data['noReset']
    desired_caps['unicodeKeyboard'] = data['unicodeKeyboard']
    desired_caps['resetKeyboard'] = data['resetKeyboard']
    desired_caps['ANDROID_UIAUTOMATOR'] = data['ANDROID_UIAUTOMATOR']
    desired_caps['chromedriverUseSystemExecutable'] = data['chromedriverUseSystemExecutable']
    desired_caps['newCommandTimeout'] = data['newCommandTimeout']
    # 连接设备
    if not check_devices([data['udid']]):
        if not adb_connect(data['udid']):
            print("连接设备失败，请检查配置文件后重试！")
            raise
    # 启动appium服务
    if not check_port(data['ip'], data['port']):
        print("端口被占用")
        release_port(data['port'])
        time.sleep(3)
    appium_start(data['ip'], data['port'])

    # 实例化driver
    driver = webdriver.Remote('http://' + str(data['ip']) + ':' + str(data['port']) + '/wd/hub', desired_caps)
    #driver.implicitly_wait(1)
    return driver


if __name__ == '__main__':
    driver = appium_desired('ths_desired_caps.yaml')
    print(driver)
